<template>
  <el-form-item id="passwordConfirm" prop="passwordConfirm" :rules="[{validator:validateUsername,trigger:'change'}]">
    <el-input type="password" v-model="passwordConfirm" :placeholder="placeholder" @input="enterInput"></el-input>
  </el-form-item>
</template>

<script>
import { validate_password } from "@/utils/validate.js";

export default {
  name: "PwConfirm",
  props: {
    placeholder:{type:String,default:"确认密码"},
    password:{type:String,default:""},
  },
  watch: {
    password: {
      handler(newValue) {
        if(newValue === this.passwordConfirm) {
          const errDom = document.getElementById("passwordConfirm").querySelector(".el-form-item__error");
          if(errDom) {
            errDom.style.display = "none";
          }   
        }
      }
    }
  },
  data() {
    return {
      passwordConfirm: ""
    }
  },
  methods: {
    enterInput() {
      let ruleStatus = validate_password(this.passwordConfirm);
      let value = ruleStatus ? this.passwordConfirm : "";
      this.$emit("update:value", value);
    },
    validateUsername(rule, value, callback) {
      // if(!this.password || this.password === "") {
      //   return callback();
      // }
      if(!this.passwordConfirm || this.passwordConfirm == "") {
        return callback(new Error("密码不能为空"));
      } else if(!validate_password(this.passwordConfirm)) {
        return callback(new Error("密码需要6~20位的数字及英文组成"));
      } else if(this.password && this.passwordConfirm !== this.password) {
        return callback(new Error("两次密码不一致"));
      } else {
        callback();
      }
    }
  }
}
</script>

<style lang="less" scoped>

</style>